package com.shj.web.security.handler;

import com.shj.model.ResResult;
import com.shj.web.util.ResultUtil;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description TODO 登录失败处理类
 * @Author songhuajian
 * @Date 2020/3/12 23:54
 **/
@Component
public class UserLoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        if (exception instanceof UsernameNotFoundException){
            ResultUtil.responseJson(response, new ResResult(500, "用户名不存在"));
        }
        if (exception instanceof LockedException){
            ResultUtil.responseJson(response, new ResResult(500, "用户被冻结"));
        }
        if (exception instanceof BadCredentialsException){
            ResultUtil.responseJson(response, new ResResult(500, "用户名或密码错误"));
        }
        ResultUtil.responseJson(response, new ResResult(500, "登录失败"));
    }
}
